import {
  Component,
  OnInit,
  trigger,
  state,
  style,
  animate,
  transition
} from '@angular/core';
import { ActivatedRoute, Router } from "@angular/router";
import { Subject } from "rxjs/Subject";
import { ReplaySubject } from "rxjs/ReplaySubject";
import { Observable } from "rxjs/Observable";
import { CmHttp } from "./../../http-module/http.service";
import { TableOptions, QuoteHeader, QuoteHeaders } from "quote";
import { SocketService, BROADCAST_EVENT } from "socket";
import { SummaryAssistantService } from "summary-assistant";
import { BROADCAST_TYPE, BroadcastService, BROADCAST_CLASSIC_PAYLOAD } from "broadcast";
import { TOGGLE_STATE } from "utils";
import { ChartTypes } from "kchart";
import { BASEURL, STOCKURL } from "shared";



const getMotherSymbol = symbol => {
  if (!symbol) return "000001.SS";
  switch (parseInt(symbol.slice(0, 1))) {
    case 6:
      return { symbol: "000001.SS", name: "上证指数" };
    case 0:
      return { symbol: "399001.SZ", name: "深圳成指" };
    case 3:
      return { symbol: "399006.SZ", name: "创业板指" };
  }
}

const scaleToCent = (num: number) => num / 100;

/**
 * QuoteTable的壳组件，给除板块类页面的QuoteTable传递参数
 * 
 * @export
 * @class QuoteCommonTableComponent
 * @implements {OnInit}
 */
@Component({

  selector: 'quote-common-table',
  templateUrl: 'quote-common-table.component.html',
  styleUrls: [
    'quote-common-table.component.less'
  ],
  animations: [
    trigger("right", [
      state(TOGGLE_STATE.EXPANDED, style({
        width: "*"
      })),
      state(TOGGLE_STATE.COLLAPSED, style({
        width: "0",
        display: "none"
      })),
      transition("COLLAPSED <=> EXPANDED", animate(200))
    ]),
    trigger("rightOfMain", [
      state(TOGGLE_STATE.EXPANDED, style({
        marginRight: "*"
      })),
      state(TOGGLE_STATE.COLLAPSED, style({
        marginRight: 1
      })),
      transition(`${TOGGLE_STATE.COLLAPSED} <=> ${TOGGLE_STATE.EXPANDED}`, animate(200))
    ]),
    trigger("bottom", [
      state(TOGGLE_STATE.EXPANDED, style({
        height: "*"
      })),
      state(TOGGLE_STATE.COLLAPSED, style({
        height: 0,
        display: "none"
      })),
      transition("COLLAPSED <=> EXPANDED", animate(200))
    ]),
    trigger("bottomOfMain", [
      state(TOGGLE_STATE.EXPANDED, style({
      })),
      state(TOGGLE_STATE.COLLAPSED, style({
      })),
      transition("COLLAPSED <=> EXPANDED", animate(200))
    ]),

  ]
})
export class QuoteCommonTableComponent implements OnInit {
  params;
  quoteToggle = new Subject();
  quoteDetailSource;
  stockDetailSource;
  quoteMotherSource;
  kChartList = [ChartTypes.MA, ChartTypes.VOL, ChartTypes.MA_VOL];
  kConfig = {
    settingBtn: false, // 是否显示设置按钮
    title: false // 是否显示股票名称
  };
  placeSource = Observable.of("quote");
  commonSort = "px_change_rate";
  outlookState = {
    "right": TOGGLE_STATE.EXPANDED,
    "bottom": TOGGLE_STATE.EXPANDED,
  };

  tableOptions: TableOptions = {
    autoClickFirst: true,
    localSort: ["name", "symbol"],
    subscribe: {
      enabled: false,
      channels: ["dynPanel"]
    },
    responsive: {
      enabled: true,
      rowHeight: 30
    },
    parts: {
      order: true,
      pagination: true
    }
  }

  //默认表头
  tableHeaders: QuoteHeaders = {
    headHeader: [
      {
        label: "序号",
        key: "$order",
        class: ["table-cell-order"]
      },
      {
        label: "名称",
        key: "prod_name",
        class: ["table-cell-name"]
      },
      // {
      //   label: "",
      //   key: "",
      //   appendModule: {
      //     module: DropdownModule,
      //     headerComponentName: "DropdownComponent",
      //     cellComponentName: "DropdownComponent",
      //   }
      // },
      {
        label: "股票代码",
        key: "symbol",
        class: ["table-cell-short"]
      }
    ],
    bodyHeader: [
      {
        label: "现价",
        key: "last_px"
      }, {
        label: "涨跌幅",
        key: "px_change_rate",
        withUpOrDown: true,
        withPercent: true
      }, {
        label: "涨跌",
        key: "px_change",
        withUpOrDown: true,
      }, {
        label: "成交量",
        key: "business_amount",
        withUnit: true,
        transform: scaleToCent
      }, {
        label: "成交额",
        key: "business_balance",
        withUnit: true,
        // }, {
        //   label: "五分钟涨跌幅",
        //   key: "min5_change",
        //   withUpOrDown: true,
        //   withPercent: true
      }, {
        label: "换手率",
        key: "turnover_ratio",
        withPercent: true
      }, {
        label: "量比",
        key: "vol_ratio",
      }, {
        label: "委比",
        key: "entrust_rate",
        withPercent: true
      }, {
        label: "振幅",
        key: "amplitude",
        withPercent: true
      }, {
        label: "内盘",
        key: "business_amount_in",
        withUnit: true,
        transform: scaleToCent
      }, {
        label: "外盘",
        key: "business_amount_out",
        withUnit: true,
        transform: scaleToCent
      }, {
        label: "流通市值",
        key: "circulation_value",
        withUnit: true
      }, {
        label: "市盈率",
        key: "pe_rate",
      }, {
        label: "市净率",
        key: "dyn_pb_rate",
      }
    ]
  };

  commonParams = {
    index: {
      id: "index",
      dataUrl: `${BASEURL}/stock/quotes/index`
    },
    hs: {
      id: "hs",
      dataUrl: `${BASEURL}/stock/quotes/market?type=0`
    },
    shanghai: {
      id: "shanghai",
      dataUrl: `${BASEURL}/stock/quotes/market?type=1`
    },
    shenzhen: {
      id: "shenzhen",
      dataUrl: `${BASEURL}/stock/quotes/market?type=2`
    },
    smse: {
      id: "smse",
      dataUrl: `${BASEURL}/stock/quotes/market?type=3`
    },
    gem: {
      id: "gem",
      dataUrl: `${BASEURL}/stock/quotes/market?type=4`
    }
  }

  constructor(
    private broadcast: BroadcastService,
    private router: ActivatedRoute,
    private goRouter: Router,
    private http: CmHttp,
    private socket: SocketService,
    private summaryAssistant: SummaryAssistantService,
  ) { }

  ngOnInit() {
    let { http, socket, summaryAssistant } = this;

    this.params = this.router.params.map(params => {
      console.debug("OK: ", params, this.commonParams[(<any>params).id])
      return this.commonParams[(<any>params).id] || this.commonParams["index"];
    });

    //下方信息
    this.quoteDetailSource = new ReplaySubject(1);
    this.quoteMotherSource = this.quoteDetailSource.map(stock => {
      return Object.assign({}, stock, getMotherSymbol(stock.symbol))
    })
    // 这部分应该放在专门的外壳组件中
    let timer = socket.broadcast.filter(e => e.event === BROADCAST_EVENT.RESET);
    Observable
      .merge(timer, this.quoteToggle).scan((acc, value) => value["symbol"] ? value : acc)
      .filter(quote => quote["symbol"])
      // this.quoteToggle
      .switchMap(quote =>
        Observable.zip(
          http.get(`${STOCKURL}/api/v2/sc/stocks/f10/${quote["symbol"]}/headlines`, {}, {cacheAge: http.CACHE_AGE.Instant}),
          // http.get(`${BASEURL}/stock/summaries/${quote["symbol"]}`, {}, {cacheAge: http.CACHE_AGE.Instant}),
          summaryAssistant.getSummaryBySymbol(quote["symbol"]),
          (fData, detail) => {
            return Object.assign({}, detail, fData.data)
          }
        )
      ).subscribe(this.quoteDetailSource);

    this.broadcast.broadcast
      .filter(action => action.type === BROADCAST_TYPE.TOGGLE_STATE)
      .subscribe(action => {
        console.debug("BROADCAST TOGGLE: ", action);
        switch (action.payload) {
          case BROADCAST_CLASSIC_PAYLOAD.TOGGLE_RIGHT:
            this.outlookState.right =
              this.outlookState.right === TOGGLE_STATE.COLLAPSED ?
                TOGGLE_STATE.EXPANDED :
                TOGGLE_STATE.COLLAPSED;
            break;
          case BROADCAST_CLASSIC_PAYLOAD.TOGGLE_BOTTOM:
            this.outlookState.bottom =
              this.outlookState.bottom === TOGGLE_STATE.COLLAPSED ?
                TOGGLE_STATE.EXPANDED :
                TOGGLE_STATE.COLLAPSED;
            break;
        }
      })
  }

  rerenderChart(e) {
    this.broadcast.broadcast.emit({
      type: BROADCAST_TYPE.RENDER_CHAERT
    })
  }

  showQuoteDetail(quote) {
    // console.debug("Quote Detail: ", quote);
    this.quoteToggle.next(quote);
  }

  goCheckDetail(quote) {
    // console.debug("Quote Db Click: ", quote);
    this.goRouter.navigate([`/stock/${quote.symbol.replace(/\./, "_")}`]);
  }

  toggleState(state: string) {
    console.debug("BROADCAST toggle: ", state);
    let states = {
      bottom: BROADCAST_CLASSIC_PAYLOAD.TOGGLE_BOTTOM
    }
    this.broadcast.broadcast.next({
      type: BROADCAST_TYPE.TOGGLE_STATE,
      payload: states[state]
    });
  }
}

